<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定时任务管理 - IoT平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
            color: #fff;
            min-height: 100vh;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 280px;
            background: rgba(16, 22, 28, 0.95);
            color: white;
            padding: 20px 0;
            position: relative;
            z-index: 10;
            box-shadow: 5px 0 15px rgba(0, 0, 0, 0.3);
        }

        .logo {
            text-align: center;
            padding: 15px 0 25px;
            font-size: 26px;
            font-weight: bold;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .logo i {
            color: #4fc3f7;
            font-size: 28px;
        }

        .menu {
            margin-top: 15px;
            padding: 0 15px;
        }

        .menu-item {
            position: relative;
            overflow: hidden;
            margin-bottom: 5px;
            border-radius: 8px;
        }

        .menu-item > a {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            color: #ecf0f1;
            text-decoration: none;
            transition: all 0.3s;
            position: relative;
            gap: 12px;
            cursor: pointer;
        }

        .menu-item > a .arrow {
            margin-left: auto;
            transition: transform 0.3s;
            font-size: 12px;
            opacity: 0.7;
        }

        .menu-item.active > a .arrow {
            transform: rotate(90deg);
        }

        .menu-item > a:hover {
            background-color: rgba(52, 152, 219, 0.2);
        }

        .menu-item.active > a {
            background: linear-gradient(90deg, rgba(41, 128, 185, 0.4), transparent);
            border-left: 4px solid #4fc3f7;
        }

        .submenu {
            display: none;
            background-color: rgba(10, 15, 20, 0.8);
            padding: 5px 0;
            border-radius: 0 0 8px 8px;
        }

        .menu-item.active .submenu {
            display: block;
        }

        .submenu a {
            display: block;
            padding: 13px 20px 13px 60px;
            color: #bdc3c7;
            text-decoration: none;
            transition: all 0.3s;
            position: relative;
            font-size: 14px;
        }

        .submenu a:before {
            content: "";
            position: absolute;
            left: 40px;
            top: 50%;
            transform: translateY(-50%);
            width: 6px;
            height: 6px;
            background: #4fc3f7;
            border-radius: 50%;
            opacity: 0.7;
        }

        .submenu a:hover {
            background-color: rgba(52, 152, 219, 0.3);
            color: white;
            padding-left: 62px;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 25px 35px;
            background-color: rgba(15, 25, 35, 0.7);
            overflow-y: auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 25px;
            background: rgba(30, 40, 50, 0.8);
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            margin-bottom: 25px;
            position: sticky;
            top: 0;
            z-index: 5;
            border: 1px solid rgba(100, 150, 200, 0.2);
        }

        .header h2 {
            color: #e0f7fa;
            font-weight: 600;
            font-size: 24px;
            text-shadow: 0 0 10px rgba(79, 195, 247, 0.5);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-info img {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #4fc3f7;
            box-shadow: 0 0 10px rgba(79, 195, 247, 0.5);
        }

        .user-info span {
            font-weight: 500;
            color: #e0f7fa;
        }

        .logout-btn {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border: none;
            padding: 13px;
            border-radius: 8px;
            cursor: pointer;
            margin-top: 20px;
            width: calc(100% - 30px);
            margin-left: 15px;
            font-weight: 500;
            font-size: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 10px rgba(231, 76, 60, 0.25);
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(231, 76, 60, 0.35);
        }

        /* 定时任务控制面板 */
        .scheduler-container {
            background: rgba(30, 40, 50, 0.7);
            border-radius: 15px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
            padding: 30px;
            border: 1px solid rgba(79, 195, 247, 0.3);
            margin-top: 20px;
        }

        .scheduler-header {
            text-align: center;
            margin-bottom: 35px;
        }

        .scheduler-header h2 {
            color: #e0f7fa;
            font-size: 32px;
            margin-bottom: 10px;
            text-shadow: 0 0 10px rgba(79, 195, 247, 0.5);
        }

        .scheduler-header p {
            color: #b0bec5;
            max-width: 700px;
            margin: 0 auto;
            line-height: 1.7;
        }

        .scheduler-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            margin-bottom: 35px;
        }

        .scheduler-card {
            background: rgba(40, 50, 60, 0.6);
            border-radius: 12px;
            padding: 25px;
            border: 1px solid rgba(79, 195, 247, 0.2);
            transition: all 0.3s;
        }

        .scheduler-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
            border-color: #4fc3f7;
        }

        .scheduler-card h3 {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #e0f7fa;
            margin-bottom: 18px;
            font-size: 20px;
        }

        .scheduler-card h3 i {
            width: 40px;
            height: 40px;
            background: rgba(79, 195, 247, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            color: #4fc3f7;
        }

        .form-group {
            margin-bottom: 22px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #e0f7fa;
            font-weight: 500;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 14px;
            background: rgba(30, 40, 50, 0.8);
            border: 1px solid rgba(79, 195, 247, 0.3);
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s;
            color: #e0f7fa;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: #4fc3f7;
            box-shadow: 0 0 0 3px rgba(79, 195, 247, 0.2);
            outline: none;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .submit-btn {
            background: linear-gradient(135deg, #4fc3f7 0%, #3498db 100%);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            font-size: 16px;
            transition: all 0.3s;
            width: 100%;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(79, 195, 247, 0.4);
        }

        .tasks-list {
            margin-top: 30px;
            background: rgba(40, 50, 60, 0.6);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid rgba(79, 195, 247, 0.2);
        }

        .tasks-list h3 {
            color: #e0f7fa;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .task-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid rgba(100, 150, 200, 0.2);
        }

        .task-info {
            flex: 1;
        }

        .task-name {
            font-weight: 600;
            color: #e0f7fa;
            margin-bottom: 5px;
        }

        .task-schedule {
            color: #b0bec5;
            font-size: 14px;
        }

        .task-actions {
            display: flex;
            gap: 10px;
        }

        .task-btn {
            padding: 8px 15px;
            border-radius: 5px;
            border: none;
            cursor: pointer;
            font-weight: 500;
        }

        .task-btn.edit {
            background: rgba(79, 195, 247, 0.2);
            color: #4fc3f7;
        }

        .task-btn.delete {
            background: rgba(231, 76, 60, 0.2);
            color: #e74c3c;
        }

        .task-btn.toggle {
            background: rgba(46, 204, 113, 0.2);
            color: #2ecc71;
        }

        .active-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .active-true {
            background-color: #2ecc71;
        }

        .active-false {
            background-color: #e74c3c;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                height: auto;
            }

            .menu {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
            }

            .menu-item {
                width: 50%;
            }

            .scheduler-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .menu-item {
                width: 100%;
            }

            .main-content {
                padding: 15px;
            }

            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 侧边栏导航 -->
<!--        <div class="sidebar">-->
<!--            <div class="logo">-->
<!--                <i class="fas fa-network-wired"></i>-->
<!--                <span>IoT定时控制平台</span>-->
<!--            </div>-->
<!--            <div class="menu">-->
<!--                <div class="menu-item">-->
<!--                    <a href="#">-->
<!--                        <i class="fas fa-tachometer-alt"></i>-->
<!--                        <span>实时监控</span>-->
<!--                        <span class="arrow"><i class="fas fa-chevron-right"></i></span>-->
<!--                    </a>-->
<!--                    <div class="submenu">-->
<!--                        <a href="#">设备状态</a>-->
<!--                        <a href="#">数据可视化</a>-->
<!--                    </div>-->
<!--                </div>-->

<!--                <div class="menu-item active">-->
<!--                    <a href="#">-->
<!--                        <i class="fas fa-sliders-h"></i>-->
<!--                        <span>设备控制</span>-->
<!--                        <span class="arrow"><i class="fas fa-chevron-right"></i></span>-->
<!--                    </a>-->
<!--                    <div class="submenu">-->
<!--                        <a href="#">远程控制</a>-->
<!--                        <a href="#">设置阈值</a>-->
<!--                        <a href="#" class="active">定时控制</a>-->
<!--                    </div>-->
<!--                </div>-->

<!--                <div class="menu-item">-->
<!--                    <a href="#">-->
<!--                        <i class="fas fa-chart-line"></i>-->
<!--                        <span>数据分析</span>-->
<!--                    </a>-->
<!--                </div>-->

<!--                <div class="menu-item">-->
<!--                    <a href="#">-->
<!--                        <i class="fas fa-tools"></i>-->
<!--                        <span>维护支持</span>-->
<!--                    </a>-->
<!--                </div>-->

<!--                <button id="logout-btn" class="logout-btn">-->
<!--                    <i class="fas fa-sign-out-alt"></i> 退出登录-->
<!--                </button>-->
<!--            </div>-->
<!--        </div>-->

        <!-- 主内容区 -->
        <div class="main-content">
            <div class="header">
                <h2>定时任务管理</h2>
                <div class="user-info">
                    <img src="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=80" alt="管理员头像">
                    <span>系统管理员</span>
                </div>
            </div>

            <!-- 定时任务控制面板 -->
            <div class="scheduler-container">
                <div class="scheduler-header">
                    <h2><i class="fas fa-clock"></i> 动态定时任务管理</h2>
                    <p>在网站运行时动态添加和管理定时任务</p>
                </div>

                <div class="scheduler-grid">
                    <div class="scheduler-card">
                        <h3><i class="fas fa-plus-circle"></i> 添加新任务</h3>
                        <div class="form-group">
                            <label for="job-id">任务ID</label>
                            <input type="text" id="job-id" placeholder="输入唯一任务ID">
                        </div>
                        <div class="form-group">
                            <label for="job-type">任务类型</label>
                            <select id="job-type">
                                <option value="interval">间隔任务</option>
                                <option value="cron">Cron表达式</option>
                                <option value="date">一次性任务</option>
                            </select>
                        </div>

                        <!-- 间隔任务参数 -->
                        <div id="interval-params" class="job-params">
                            <div class="form-group">
                                <label for="interval-seconds">间隔时间(秒)</label>
                                <input type="number" id="interval-seconds" min="1" value="300">
                            </div>
                        </div>

                        <!-- Cron任务参数 -->
                        <div id="cron-params" class="job-params" style="display:none;">
                            <div class="form-group">
                                <label for="cron-expression">Cron表达式</label>
                                <input type="text" id="cron-expression" placeholder="* * * * *">
                                <small style="color: #b0bec5;">(分 时 日 月 周)</small>
                            </div>
                        </div>

                        <!-- 一次性任务参数 -->
                        <div id="date-params" class="job-params" style="display:none;">
                            <div class="form-group">
                                <label for="run-date">执行时间</label>
                                <input type="datetime-local" id="run-date">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="job-function">任务函数</label>
                            <select id="job-function">
                                <option value="analyze_data_task">数据分析任务</option>
                                <option value="backup_database_task">数据库备份任务</option>
                                <option value="cleanup_logs_task">日志清理任务</option>
                                <option value="generate_report_task">报告生成任务</option>
                            </select>
                        </div>

                        <button class="submit-btn" id="add-job-btn">
                            <i class="fas fa-plus"></i> 添加定时任务
                        </button>
                    </div>

                    <div class="scheduler-card">
                        <h3><i class="fas fa-info-circle"></i> 任务说明</h3>
                        <div class="job-info">
                            <h4>任务类型说明</h4>
                            <ul style="padding-left: 20px; margin-bottom: 20px; color: #b0bec5;">
                                <li><strong>间隔任务</strong>: 按固定时间间隔执行任务</li>
                                <li><strong>Cron任务</strong>: 使用Cron表达式定义执行时间</li>
                                <li><strong>一次性任务</strong>: 在特定时间执行一次任务</li>
                            </ul>

                            <h4>可用任务函数</h4>
                            <ul style="padding-left: 20px; color: #b0bec5;">
                                <li><strong>数据分析任务</strong>: 分析物联网数据并生成报告</li>
                                <li><strong>数据备份任务</strong>: 备份数据库到云端存储</li>
                                <li><strong>数据清理任务</strong>: 清理过期日志和临时数据</li>
                                <li><strong>报告生成任务</strong>: 生成每日系统运行报告</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="tasks-list">
                    <h3><i class="fas fa-tasks"></i> 当前定时任务</h3>
                    <div id="jobs-container">
                        <!-- 任务列表将通过JavaScript动态填充 -->
                        <div class="task-item">
                            <div class="task-info">
                                <div class="task-name">
                                    <span class="active-indicator active-true"></span>
                                    数据分析任务 (每5分钟)
                                </div>
                                <div class="task-schedule">任务ID: job1 | 类型: interval | 间隔: 300秒</div>
                            </div>
                            <div class="task-actions">
                                <button class="task-btn toggle">暂停</button>
                                <button class="task-btn delete">删除</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 菜单交互功能
        document.querySelectorAll('.menu-item > a').forEach(item => {
            if (item.parentElement.querySelector('.submenu')) {
                const arrow = document.createElement('span');
                arrow.className = 'arrow';
                arrow.innerHTML = '<i class="fas fa-chevron-right"></i>';
                item.appendChild(arrow);

                item.addEventListener('click', function(e) {
                    e.preventDefault();
                    document.querySelectorAll('.menu-item').forEach(i => {
                        if (i !== this.parentElement) {
                            i.classList.remove('active');
                        }
                    });
                    this.parentElement.classList.toggle('active');
                });
            }
        });

        // 任务类型切换
        document.getElementById('job-type').addEventListener('change', function() {
            // 隐藏所有参数区域
            document.querySelectorAll('.job-params').forEach(el => {
                el.style.display = 'none';
            });

            // 显示当前选择的参数区域
            const selectedType = this.value;
            document.getElementById(`${selectedType}-params`).style.display = 'block';
        });

        // 添加任务按钮事件
        document.getElementById('add-job-btn').addEventListener('click', addNewJob);

        // 添加新任务函数
// 添加新任务函数
            async function addNewJob() {
                const jobId = document.getElementById('job-id').value;
                const jobType = document.getElementById('job-type').value;
                const jobFunction = document.getElementById('job-function').value;

                if (!jobId) {
                    alert('请输入任务ID');
                    return;
                }

                // 根据任务类型获取参数
                let triggerArgs = {};
                switch(jobType) {
                    case 'interval':
                        const seconds = parseInt(document.getElementById('interval-seconds').value);
                        if (isNaN(seconds) || seconds <= 0) {
                            alert('请输入有效的间隔时间（秒）');
                            return;
                        }
                        triggerArgs = { 'seconds': seconds };
                        break;

                    case 'cron':
                        const cronExpression = document.getElementById('cron-expression').value;
                        if (!cronExpression) {
                            alert('请输入Cron表达式');
                            return;
                        }
                        triggerArgs = { 'cron': cronExpression };
                        break;

                    case 'date':
                        const runDate = document.getElementById('run-date').value;
                        if (!runDate) {
                            alert('请选择执行时间');
                            return;
                        }
                        triggerArgs = { 'run_date': new Date(runDate).toISOString() };
                        break;
                }

                try {
                    // 发送请求到后端添加任务
                    const response = await fetch('/api/jobs/add', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            job_id: jobId,
                            job_type: jobType,
                            job_function: jobFunction,
                            trigger_args: triggerArgs
                        })
                    });

                    const result = await response.json();

                    if (response.ok) {
                        alert(`任务 "${jobId}" 添加成功！`);
                        // 刷新任务列表
                        loadJobs();
                        // 重置表单
                        document.getElementById('job-id').value = '';
                    } else {
                        alert(`添加任务失败: ${result.error}`);
                    }
                } catch (error) {
                    console.error('添加任务时出错:', error);
                    alert('添加任务失败，请检查网络连接');
                }
            }

            // 加载任务列表
            async function loadJobs() {
                try {
                    const response = await fetch('/api/jobs');
                    const jobs = await response.json();

                    const container = document.getElementById('jobs-container');
                    container.innerHTML = '';

                    if (jobs.length === 0) {
                        container.innerHTML = '<div class="no-jobs">没有定时任务</div>';
                        return;
                    }

                    jobs.forEach(job => {
                        const jobItem = document.createElement('div');
                        jobItem.className = 'task-item';

                        let scheduleText = '';
                        if (job.trigger === 'interval') {
                            scheduleText = `类型: 间隔任务 | 间隔: ${job.trigger_args.seconds}秒`;
                        } else if (job.trigger === 'cron') {
                            scheduleText = `类型: Cron任务 | 表达式: ${job.trigger_args.cron}`;
                        } else if (job.trigger === 'date') {
                            scheduleText = `类型: 一次性任务 | 时间: ${new Date(job.trigger_args.run_date).toLocaleString()}`;
                        }

                        jobItem.innerHTML = `
                            <div class="task-info">
                                <div class="task-name">
                                    <span class="active-indicator ${job.active ? 'active-true' : 'active-false'}"></span>
                                    ${job.func} (${job.id})
                                </div>
                                <div class="task-schedule">${scheduleText}</div>
                                <div class="task-next-run">下次执行: ${job.next_run || '无'}</div>
                            </div>
                            <div class="task-actions">
                                <button class="task-btn toggle" data-id="${job.id}" data-active="${job.active}">
                                    ${job.active ? '暂停' : '启用'}
                                </button>
                                <button class="task-btn delete" data-id="${job.id}">删除</button>
                            </div>
                        `;

                        container.appendChild(jobItem);
                    });

                    // 添加事件监听器
                    document.querySelectorAll('.task-btn.delete').forEach(btn => {
                        btn.addEventListener('click', deleteJob);
                    });

                    document.querySelectorAll('.task-btn.toggle').forEach(btn => {
                        btn.addEventListener('click', toggleJob);
                    });

                } catch (error) {
                    console.error('加载任务列表失败:', error);
                    const container = document.getElementById('jobs-container');
                    container.innerHTML = '<div class="error">加载任务列表失败</div>';
                }
            }

            // 删除任务
            async function deleteJob(e) {
                const jobId = e.target.dataset.id;
                if (confirm(`确定要删除任务 "${jobId}" 吗？`)) {
                    try {
                        const response = await fetch(`/api/jobs/${jobId}`, {
                            method: 'DELETE'
                        });

                        if (response.ok) {
                            alert(`任务 "${jobId}" 已删除`);
                            loadJobs();
                        } else {
                            const result = await response.json();
                            alert(`删除任务失败: ${result.error}`);
                        }
                    } catch (error) {
                        console.error('删除任务时出错:', error);
                        alert('删除任务失败');
                    }
                }
            }

            // 切换任务状态
            async function toggleJob(e) {
                const jobId = e.target.dataset.id;
                const isActive = e.target.dataset.active === 'true';

                try {
                    const response = await fetch(`/api/jobs/${jobId}/toggle`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            active: !isActive
                        })
                    });

                    if (response.ok) {
                        alert(`任务 "${jobId}" 已${isActive ? '暂停' : '启用'}`);
                        loadJobs();
                    } else {
                        const result = await response.json();
                        alert(`操作失败: ${result.error}`);
                    }
                } catch (error) {
                    console.error('切换任务状态时出错:', error);
                    alert('操作失败');
                }
            }

            // 页面加载完成后执行
            document.addEventListener('DOMContentLoaded', function() {
                // 加载任务列表
                loadJobs();

                // 设置退出登录按钮事件
                document.getElementById('logout-btn').addEventListener('click', function() {
                    if (confirm('确定要退出登录吗？')) {
                        window.location.href = '/logout';
                    }
                });
            });
    </script>
</body>
</html>